/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package skat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.swing.event.EventListenerList;

import rlpw.util.Pair;
import skat.event.DeskEvent;
import skat.event.DeskListener;
import skat.games.Game;
import skat.player.Player;

/**
 *
 * @author weinpau
 */
public class Desk extends ArrayList<Pair<Player, Card>> {

    private final Game game;
    private EventListenerList listeners = new EventListenerList();

    public Desk(Game game) {
        this.game = game;
    }

    public Game getGame() {
        return game;
    }

    public boolean isTrumpIncluding() {

        for (Pair<Player, Card> p : this) {
            if (game.isTrumpCard(p.right())) {
                return true;
            }
        }
        return false;
    }

    public Pair<Player, Card> getHighestPair() {

        if (isEmpty()) {
            return null;
        } else {
            Desk comp = (Desk) clone();
            if (isTrumpIncluding()) {
                Collections.sort(comp, game);
            } else {

                for (Pair<Player, Card> p : this) {
                    if (p.right().suit() != comp.get(0).right().suit()) {
                        comp.remove(p);
                    }
                }
                Collections.sort(comp, game);
            }
            return comp.get(0);
        }

    }

    @Override
    public boolean add(Pair<Player, Card> e) {

        boolean result = super.add(e);
        if (result) {
            notifyAdvertisement(new DeskEvent(this, e.left(), e.right()));
        }
        return result;
    }

    public Card getFirstCard() {
        if (isEmpty()) {
            return null;
        } else {
            return get(0).right();
        }
    }

    public int getPoints() {
        int p = 0;
        for (Pair<Player, Card> pair : this) {
            p += pair.right().value();
        }
        return p;
    }

    public void addDeskListener(DeskListener listener) {
        listeners.add(DeskListener.class, listener);
    }

    public void removeDeskListener(DeskListener listener) {
        listeners.remove(DeskListener.class, listener);
    }

    protected synchronized void notifyAdvertisement(DeskEvent event) {
        for (DeskListener l : listeners.getListeners(DeskListener.class)) {
            l.deskAddingCard(event);
        }
    }

    public Collection<Card> getAllCards() {
        Collection<Card> cc = new ArrayList<Card>();
        for (Pair<Player, Card> p : this) {
            cc.add(p.right());
        }
        return cc;
    }
}
